package com.qiantu.phone.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.qiantu.phone.R;


/**
 * @Package: com.luzx.base.widget
 * @ClassName: EditTextLayout
 * @Description: 描述
 * @Author: luzx
 * @CreateDate: 2020/9/28 14:44
 * @UpdateUser: luzx
 * @UpdateDate: 2020/9/28 14:44
 * @UpdateRemark: 更新说明
 */
public class EditTextLayout extends FrameLayout {

    public EditText mEditText;

    private int textColor;

    private int hintTextColor;

    private float textSize;

    private int paddingLeft;

    private int paddingRight;

    private int paddingTop;

    private int paddingBottom;

    private int inputType;

    private int textStyle;

    private int maxLength;

    private int maxLines;

    private int gravity;

    private int imeOptions;

    private int editDeleteIcon;
    private boolean iconVisible;

    private int editSwitchPasswordIcon;

    private int editLeftIcon;

    private int editLeftIconPadding;

    private int editSwitchIconMarginLeft;

    private int editSwitchIconMarginRight;

    private ImageView deleteIcon;

    private ImageView switchPasswordIcon;

    private String hint;

    private View rightBtnContainer;

    private boolean hasSetEditPadding;

    public EditTextLayout(Context context) {
        this(context, null);
    }

    public EditTextLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("ResourceType")
    public EditTextLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.EditTextLayout);
        hint = mTypedArray.getString(R.styleable.EditTextLayout_custom_hint);
        textColor = mTypedArray.getColor(R.styleable.EditTextLayout_custom_text_color, 0xff666666);
        hintTextColor = mTypedArray.getColor(R.styleable.EditTextLayout_custom_hint_color, 0xff999999);
        textSize = mTypedArray.getDimension(R.styleable.EditTextLayout_custom_text_size, 30);
        inputType = mTypedArray.getInt(R.styleable.EditTextLayout_android_inputType, -1);
        textStyle = mTypedArray.getInt(R.styleable.EditTextLayout_android_textStyle, Typeface.NORMAL);
        maxLength = mTypedArray.getInt(R.styleable.EditTextLayout_android_maxLength, -1);
        maxLines = mTypedArray.getInt(R.styleable.EditTextLayout_android_maxLines, -1);
        gravity = mTypedArray.getInt(R.styleable.EditTextLayout_android_gravity, Gravity.CENTER_VERTICAL);
        imeOptions = mTypedArray.getInt(R.styleable.EditTextLayout_android_imeOptions, EditorInfo.IME_ACTION_NONE);
        iconVisible = mTypedArray.getBoolean(R.styleable.EditTextLayout_right_icon_visible, true);
        editDeleteIcon = mTypedArray.getResourceId(R.styleable.EditTextLayout_custom_edit_delete_icon, 0);
        editSwitchPasswordIcon = mTypedArray.getResourceId(R.styleable.EditTextLayout_custom_edit_switch_password_icon, 0);
        editSwitchIconMarginLeft = (int) (mTypedArray.getDimension(R.styleable.EditTextLayout_custom_edit_switch_icon_margin_left, 0) + 0.5f);
        editSwitchIconMarginRight = (int) (mTypedArray.getDimension(R.styleable.EditTextLayout_custom_edit_switch_icon_margin_right, 0) + 0.5f);
        editLeftIcon = mTypedArray.getResourceId(R.styleable.EditTextLayout_custom_edit_left_icon, 0);
        editLeftIconPadding = (int) (mTypedArray.getDimension(R.styleable.EditTextLayout_custom_edit_left_icon_padding, 0) + 0.5f);

        float dp5 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5,  getResources().getDisplayMetrics());
        float dp12 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12,  getResources().getDisplayMetrics());
        paddingLeft = (int) (mTypedArray.getDimension(R.styleable.EditTextLayout_custom_padding_left, dp5) + 0.5f);
        paddingRight = (int) (mTypedArray.getDimension(R.styleable.EditTextLayout_custom_padding_right, dp5) + 0.5f);
        paddingTop = (int) (mTypedArray.getDimension(R.styleable.EditTextLayout_custom_padding_top, dp12) + 0.5f);
        paddingBottom = (int) (mTypedArray.getDimension(R.styleable.EditTextLayout_custom_padding_bottom, dp12) + 0.5f);
        mTypedArray.recycle();

        init(context);
    }

    private void init(Context context){
        View rootView = LayoutInflater.from(context).inflate(R.layout.edit_text_layout, this, true);
        mEditText = rootView.findViewById(R.id.edit_text);
        rightBtnContainer = rootView.findViewById(R.id.right_btn_container);
        rightBtnContainer.setVisibility(iconVisible? VISIBLE : GONE);
        mEditText.setCompoundDrawablePadding(editLeftIconPadding);
        mEditText.setCompoundDrawablesWithIntrinsicBounds(editLeftIcon, 0, 0, 0);
        mEditText.setHint(hint);
        mEditText.setImeOptions(imeOptions);
        mEditText.setGravity(gravity);
        mEditText.setTextColor(textColor);
        mEditText.setHintTextColor(hintTextColor);
        mEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        if(maxLength >= 0){
            InputFilter[] filters = { new InputFilter.LengthFilter(maxLength) };
            mEditText.setFilters(filters);
        }
        if(maxLines > 0){
            mEditText.setMaxLines(maxLines);
            mEditText.setEllipsize(TextUtils.TruncateAt.END);
            mEditText.setSingleLine();
        }
        deleteIcon = rootView.findViewById(R.id.edit_password_clear);
        if(editDeleteIcon != 0){
            deleteIcon.setImageResource(editDeleteIcon);
        }
        switchPasswordIcon = rootView.findViewById(R.id.switch_password_type);
        if(editSwitchPasswordIcon != 0){
            switchPasswordIcon.setImageResource(editSwitchPasswordIcon);
        }
        LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) switchPasswordIcon.getLayoutParams();
        ll.leftMargin = editSwitchIconMarginLeft;
        ll.rightMargin = editSwitchIconMarginRight;
        if(inputType != -1){
            mEditText.setInputType(inputType);
        }
        mEditText.setTypeface(mEditText.getTypeface(), textStyle);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    deleteIcon.setVisibility(VISIBLE);
                    if(isPasswordInputType(inputType)){
                        switchPasswordIcon.setVisibility(VISIBLE);
                    }
                    //有一位就显示delete icon重新设置paddingRight，后续不再设置了
                    if(s.length() > 0 && !hasSetEditPadding){
                        setEditPadding();
                        hasSetEditPadding = true;
                    }
                    mEditText.setSelected(true);
                }else{
                    //清空就隐藏delete icon重新设置paddingRight，后续不再设置了
                    deleteIcon.setVisibility(GONE);
                    switchPasswordIcon.setVisibility(GONE);
                    hasSetEditPadding = false;
                    //隐藏delete就清除paddingRight
                    setEditPadding();
                    mEditText.setSelected(false);
                }
            }
        });
        deleteIcon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditText.setText(null);
                mEditText.requestFocus();
            }
        });

        if(isPasswordInputType(inputType)){
            switchPasswordIcon.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.isSelected()) {
                        mEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        v.setSelected(false);
                    } else {
                        mEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        v.setSelected(true);
                    }
                    mEditText.setSelection(mEditText.getText().toString().length());
                    mEditText.requestFocus();
                }
            });
        }else{
            switchPasswordIcon.setVisibility(GONE);
        }
        setEditPadding();
    }

    public void setIconVisible(boolean b){
        rightBtnContainer.setVisibility(b?VISIBLE:GONE);
    }

    private void setEditPadding(){
        rightBtnContainer.measure(0,0);
        mEditText.setPadding(paddingLeft, paddingTop, paddingRight + rightBtnContainer.getMeasuredWidth(), paddingBottom);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        mEditText.getLayoutParams().height = getMeasuredHeight();
    }

    private boolean isPasswordInputType(int inputType) {
        final int variation =
                inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION);
        return variation
                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)
                || variation
                == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD)
                || variation
                == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
    }

    public void setText(String text){
        mEditText.setText(text);
    }

    public void setText(int text){
        mEditText.setText(text);
    }

    public CharSequence getText(){
        return mEditText.getText();
    }

    public void setTextColor(int color){
        mEditText.setTextColor(color);
    }

    public void setHintTextColor(int color){
        mEditText.setHintTextColor(color);
    }

    public void setHint(String hint) {
        this.hint = hint;
        mEditText.setHint(hint);
    }

    public EditText getEditText() {
        return mEditText;
    }

    public void setEnabled(boolean enabled){
        super.setEnabled(enabled);
        mEditText.setEnabled(enabled);
        if(enabled){
            if(mEditText.getText().length() > 0){
                deleteIcon.setVisibility(VISIBLE);
            }
            if(isPasswordInputType(inputType)) {
                switchPasswordIcon.setVisibility(VISIBLE);
            }
            setEditPadding();
        }else{
            deleteIcon.setVisibility(GONE);
            switchPasswordIcon.setVisibility(GONE);
            setEditPadding();
        }
    }

    public void setLongClickable(){
        mEditText.setLongClickable(false);
        mEditText.setTextIsSelectable(false);
    }
}
